package com.example.mooctao.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mooctao.R;
import com.example.mooctao.util.DataUtil;
import com.example.mooctao.util.IndexViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//首页
public class IndexFragment extends Fragment {
    private ViewPager2 pagers_top;
    private LinearLayout pointers;
    private int index = 1;//用于保存一个数字，控制ViewPager的显示页数
    private GridView grids;
    private List<Map<String, Object>> data = new ArrayList<>();
    private List<Map<String, Object>> data1 = new ArrayList<>();
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private IndexViewModel viewModel;
    private EditText etSearch;
    private ImageView btnSearch;

//创建视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_index, container, false);



        //初始化控件
        //轮播图控件
        pagers_top = v.findViewById(R.id.pagers_top);
        pointers = v.findViewById(R.id.pointers);
        //一级菜单控件
        grids = v.findViewById(R.id.index_grids);
        /// 二级菜单控件
        recyclerView = (RecyclerView) v.findViewById(R.id.pagers_menu);
        layoutManager = new LinearLayoutManager(getContext());
        //从ViewModel获取数据
        viewModel = new ViewModelProvider(this).get(IndexViewModel.class);
        data = viewModel.getData() != null ? viewModel.getData() : new ArrayList<>();
        data1 = viewModel.getData1() != null ? viewModel.getData1() : new ArrayList<>();
        initData();
        setViewPager();
        setGridView();
        setMenuDate();
        setMenuPager();

        return v;
    }

    //初始化数据
    private void initData() {
        if (data.isEmpty()) {
            for (int i = 0; i < DataUtil.index_menu1_imgs.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("img", DataUtil.index_menu1_imgs[i]);
                map.put("txt", DataUtil.index_menu1_txts[i]);
                data.add(map);
            }
            viewModel.setData(data);
        }
    }

    //设置一级菜单
    private void setGridView() {

        String[] from = {"img", "txt"};
        int[] to = {R.id.index_image_grid, R.id.index_text_grid};
        SimpleAdapter adapter = new SimpleAdapter(getContext(), data, R.layout.index_menu_grid, from, to);
        grids.setAdapter(adapter);
    }

    //设置二级菜单数据
    private void setMenuDate() {
        if (data1.isEmpty()) {
            for (int i = 0; i < DataUtil.index_menu2_imgs.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("img", DataUtil.index_menu2_imgs[i]);
                map.put("txt", DataUtil.index_menu2_txts[i]);
                data1.add(map);
            }
            viewModel.setData1(data1);
        }
    }

    //二级菜单
    private void setMenuPager() {
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
//onCreateViewHolder 方法创建并返回每个列表项的视图，onBindViewHolder 方法根据当前项的位置绑定数据（图片和文本）到视图中。
        RecyclerView.Adapter adapter = new RecyclerView.Adapter() {

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View v = LayoutInflater.from(getContext()).inflate(R.layout.menu_item, parent, false);
                return new ViewHolder(v);
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                ViewHolder vh = (ViewHolder) holder;
                // 获取对应位置的数据
                // 确保 position 小于 data 的大小
                if (position < data1.size()) {
                    Map<String, Object> menuItem = data1.get(position);
                    int imgResId = (int) menuItem.get("img");
                    String txt = (String) menuItem.get("txt");

                    // 设置图像和文本
                    vh.img1.setImageResource(imgResId);
                    vh.txt1.setText(txt);
                }

            }

            @Override
            public int getItemCount() {
                return data1.size();  // 返回数据项的数量
            }
        };
    //recyclerView.setAdapter(adapter) 将定义好的 Adapter 设置到 RecyclerView 上。
        recyclerView.setAdapter(adapter);
    }

    //设置广告图片轮播
    private void setViewPager() {

        //实现图片滑动轮播
        RecyclerView.Adapter adapter = new RecyclerView.Adapter() {

            //用于获取盛放图片的控件的ViewHolder对象
            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                //创建一个空白布局，将轮播的图片设置为布局的背景图片
                View v = LayoutInflater.from(getContext()).inflate(R.layout.adv_item, parent, false);
                return new ViewHolder(v);
            }

            //为ViewHolder对象中的控件设置显示效果
            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                ViewHolder vh = (ViewHolder) holder;
                int imgResId = DataUtil.adv_imgs[position % DataUtil.adv_imgs.length]; // 确保索引在范围内
                vh.v.setBackgroundResource(imgResId);

                // 设置点击事件
                vh.v.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putInt("image", DataUtil.adv_imgs[position % 4]); // 传递图片资源ID
                    bundle.putString("title", DataUtil.adv_titles[position % 4]); // 传递标题
                    bundle.putString("content", DataUtil.adv_descriptions[position % 4]); // 传递内容

                    NewsDetailFragment newsDetailFragment = new NewsDetailFragment();
                    newsDetailFragment.setArguments(bundle);

                    getParentFragmentManager().beginTransaction()
                            .replace(R.id.container, newsDetailFragment)
                            .addToBackStack(null)
                            .commit();
                });

            }


            //设置pager的数量
            @Override
            public int getItemCount() {
                return Integer.MAX_VALUE;
            }
        };

        pagers_top.setAdapter(adapter);

        //滑动事件：同步指示器、修改自动轮播位置
        pagers_top.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                for (int i = 0; i < pointers.getChildCount(); i++) {
                    //先将所有指示器设置为未选中状态
                    ImageView img = (ImageView) pointers.getChildAt(i);
                    img.setImageResource(R.drawable.dot_unselected);
                }
                //position位置对应的指示器设置为选中状态
                ((ImageView) pointers.getChildAt(position % 4)).setImageResource(R.drawable.dot_selected);
                //将index设置为当前位置
                index = position;
            }
        });

        //通过线程来实现自动轮播
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (true) {
                    try {
                        sleep(6000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    pagers_top.setCurrentItem(index);
                    index++;
                }
            }
        }.start();
    }

//    这个 ViewHolder 类的作用是缓存每个列表项的视图组件（如 ImageView 和 TextView）。通过 findViewById() 查找视图并缓存它们，
//    避免在每次滚动时重新查找视图，从而提高 RecyclerView 的性能。
    class ViewHolder extends RecyclerView.ViewHolder {
        public View v;
        public ImageView img1;
        public TextView txt1;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            v = itemView;
            img1 = itemView.findViewById(R.id.image1_menu2);
            txt1 = itemView.findViewById(R.id.text1_menu2);

        }
    }


}
